<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <el-button
        v-if="formType.includes('create')"
        class="mr-5px"
        @click="submitForm"
        type="primary"
        v-hasPermi="['produce:production-incoming:save']"
        :disabled="formLoading"
        >保 存</el-button
      >
      <el-button
        v-if="formType.includes('update')"
        class="mr-5px"
        @click="submitForm"
        type="primary"
        v-hasPermi="['produce:production-incoming:delete']"
        :disabled="formLoading"
        >删 除</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        v-loading="formLoading"
        class="pb-6px"
      >
        <el-form-item label="部件选择" v-if="!formType.includes('view')">
          <el-button @click="selectPiece(formData.orderNumber)" type="primary">部件选择</el-button>
        </el-form-item>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input disabled v-model="formData.orderNumber" placeholder="订单号" />
        </el-form-item>
        <el-form-item label="订单类型" prop="dictOrderType">
          <el-select
            suffix-icon=""
            disabled
            v-model="formData.dictOrderType"
            placeholder="订单类型"
            clearable
            class="!w-220px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions('market_order_type')"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户代码" prop="customerCode">
          <el-input disabled v-model="formData.customerCode" placeholder="客户代码" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input disabled v-model="formData.customerName" placeholder="客户名称" />
        </el-form-item>
        <el-form-item label="产品编码" prop="productNumber">
          <el-input disabled v-model="formData.productNumber" placeholder="产品编码" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input disabled v-model="formData.productName" placeholder="产品名称" />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input disabled v-model="formData.productStandard" placeholder="产品规格" />
        </el-form-item>
        <el-form-item label="部件编码" prop="partNumber">
          <el-input disabled v-model="formData.partNumber" placeholder="部件编码" />
        </el-form-item>
        <el-form-item label="部件名称" prop="partName">
          <el-input disabled v-model="formData.partName" placeholder="部件名称" />
        </el-form-item>
        <el-form-item label="部件规格" prop="partSpecification">
          <el-input disabled v-model="formData.partSpecification" placeholder="部件规格" />
        </el-form-item>
        <el-form-item label="订单数量" prop="orderQuantity">
          <el-input disabled v-model="formData.orderQuantity" placeholder="订单数量" />
        </el-form-item>
        <el-form-item label="剩余订单数量" prop="orderRemaQuantity">
          <el-input disabled v-model="formData.orderRemaQuantity" placeholder="剩余订单数量" />
        </el-form-item>
        <el-form-item label="图纸图号" prop="drawingNumber">
          <el-input disabled v-model="formData.drawingNumber" placeholder="图纸图号" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-select
            :disabled="formType.includes('view')"
            v-model="formData.warehouseName"
            filterable
            remote
            reserve-keyword
            placeholder="请选择仓库名称"
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="(item, index) in optionsWarehouseName"
              :key="index"
              :label="item.warehouseName"
              :value="item.warehouseName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库数量" prop="incomingQuantity">
          <el-input-number
            :disabled="formType.includes('view')"
            controls-position="right"
            :min="0"
            @change="incomingBtn"
            v-model="formData.incomingQuantity"
            placeholder="请输入入库数量"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="单位" prop="dictUnit">
          <el-select
            suffix-icon=""
            disabled
            v-model="formData.partUnit"
            placeholder="单位"
            clearable
            class="!w-220px"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions('order_product_unit')"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <ProductionIncomingDialog ref="incomingRef" @success="getIncomingData" />
  </div>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as ProductionIncomingApi from '@/api/produce/productManagement/productionIncoming'
import { useTagsViewStore } from '@/store/modules/tagsView'
import ProductionIncomingDialog from './ProductionIncomingDialog.vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const optionsWarehouseName = ref<any[]>([]) // 仓库名称
const { query } = useRoute() // 路由的查询
const loading = ref(false)
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  selectedPartId: undefined,
  orderNumber: undefined,
  dictOrderType: undefined,
  customerCode: undefined,
  customerName: undefined,
  productNumber: undefined,
  productName: undefined,
  productStandard: undefined,
  partNumber: undefined,
  partName: undefined,
  partSpecification: undefined,
  orderQuantity:undefined,
  orderRemaQuantity: undefined,
  incomingQuantity: undefined,
  partUnit: undefined,
  warehouseCode: undefined,
  warehouseName: undefined,
  creatorName: undefined,
  updaterName: undefined,
  drawingNumber:undefined
})
const formRules = reactive({
  warehouseName: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
  incomingQuantity: [{ required: true, message: '入库数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const getData = async () => {
  // dialogTitle.value = t('action.' + type)
  formType.value = (query as any).type
  const id = Number(query.id)
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductionIncomingApi.getProductionIncoming(id)
    } finally {
      formLoading.value = false
    }
  }
}

// 处理人
const remoteMethod = async (keyword: string) => {
  loading.value = true
  try {
    const data = await ProductionIncomingApi.enableSimpleAllList(keyword)
    optionsWarehouseName.value = data
  } finally {
    loading.value = false
  }
}

// 输入的入库
const incomingBtn = (val) => {
  // formData.orderQuantity
  if (val < 0) {
    message.notifyError('入库数量不能小于0')
    formData.value.incomingQuantity = undefined
  }
  // else if (val === 0) {
  //   message.notifyError('入库数量不能为0')
  //   formData.value.incomingQuantity = undefined
  // }
}

// 打开选择部件
const incomingRef = ref()
const selectPiece = (val) => {
  incomingRef.value.open(val)
}

// 选择部件数据
const getIncomingData = (data) => {
  formData.value = data
  formData.value.selectedPartId = data.id
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductionIncomingApi.ProductionIncomingVO
    if(!data.incomingQuantity || data.incomingQuantity <= 0) {
        message.error('入库数量需大于0')
        return 
    }
    if (!data.warehouseCode) {
      optionsWarehouseName.value.map((item) => {
        if (item.warehouseName == data.warehouseName) {
          data.warehouseCode = item.warehouseCode
        }
      })
    }
    
    if (formType.value === 'create') {
      await ProductionIncomingApi.createProductionIncoming(data)
      message.success(t('common.createSuccess'))
      goBack()
    } else {
      data.id = Number(query.id)
      // await ProductionIncomingApi.updateProductionIncoming(data)
      await ProductionIncomingApi.deleteProductionIncoming(data.id)
      message.success(t('common.delSuccess'))
      goBack()
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    selectedPartId: undefined,
    orderNumber: undefined,
    dictOrderType: undefined,
    customerCode: undefined,
    customerName: undefined,
    productNumber: undefined,
    productName: undefined,
    productStandard: undefined,
    partNumber: undefined,
    partName: undefined,
    partSpecification: undefined,
    orderQuantity:undefined,
    orderRemaQuantity: undefined,
    incomingQuantity: undefined,
    dictUnit: undefined,
    warehouseCode: undefined,
    warehouseName: undefined,
    creatorName: undefined,
    updaterName: undefined,
    drawingNumber:undefined
  }
  formRef.value?.resetFields()
}

/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/produce/produce/productManagement/productionIncoming'
  })
}

const contentHeight = ref(0)
onMounted(() => {
  contentHeight.value = document.body.clientHeight - 127
  getData()
})
</script>
